package cn.wolfcode.service.impl;

import cn.wolfcode.domain.Department;
import cn.wolfcode.domain.Employee;
import cn.wolfcode.exception.LogicException;
import cn.wolfcode.mapper.EmployeeMapper;
import cn.wolfcode.qo.PageResult;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IEmployeeService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Collections;
import java.util.List;

@Service
public class EmployeeServiceImpl implements IEmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;


    @Transactional
    public void save(Employee employee, Long[] ids) {
        //除了往employee 中存入数据
        employeeMapper.insert(employee);
        //还要往中间表employee_role表存入数据
        interRelation(employee, ids);

    }

    @Transactional
    public void delete(Long id) {

        // 从中间表 role_permission 中删除与此角色相关的关系数据
        employeeMapper.deleteRelation(id);
        employeeMapper.deleteByPrimaryKey(id);
    }


    @Transactional
    public void update(Employee employee, Long[] ids) {
        //修改员工表数据
        employeeMapper.updateByPrimaryKey(employee);
        // 删除中间表 employee_role 中旧的关系数据
        employeeMapper.deleteRelation(employee.getId());
        if (ids != null && ids.length > 0) {
            for (Long roleId : ids) {
                // 往中间表 employee_role 插入关系数据
                employeeMapper.insertRelation(employee.getId(), roleId);
            }
        }
    }


    private void interRelation(Employee employee, Long[] ids) {
        if (ids != null && ids.length > 0) {
            for (Long roleId : ids) {
                // 往中间表 employee_role 插入新的关系数据
                employeeMapper.insertRelation(employee.getId(), roleId);
            }
        }
    }

    @Transactional
    public Employee get(Long id) {

        return employeeMapper.selectByPrimaryKey(id);
    }

    @Transactional
    public List<Employee> listAll() {
        return employeeMapper.selectAll();
    }

    @Transactional
    public PageInfo<Employee> query(QueryObject qo) {
        //告诉Mybatis分页插件 设置查询第几页,每页多少条
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize());
        List<Employee> employees = employeeMapper.selectForList(qo);
        return new PageInfo<Employee>(employees);
    }


    public Employee login(String username, String password) {
        //调用业务
        if (!StringUtils.hasText(username)) {
            throw new LogicException("用户名不能为空");
        }
        // 查询数据库中是否有匹配的数据
        Employee employee = employeeMapper.selectByUsernameAndPassword(
                username,
                password);
        if (employee == null) {
            //通知调用者出现异常
            throw new LogicException("账号和密码不匹配");
        }
        return employee;
    }

    @Override
    public void batchDelete(Long[] ids) {
        employeeMapper.batchDelete(ids);
    }

    @Override
    public Employee selectByName(String name) {

        return employeeMapper.selectByName(name);
    }





    //实现导出的功能
    public Workbook exportXls() {
        //创建工作簿对象
        HSSFWorkbook wb = new HSSFWorkbook();
        //创建excel文件,工作表
        HSSFSheet sheet = wb.createSheet("员工通讯录");
        //查询员工数据
        List<Employee> employees = employeeMapper.selectAll();
        //创建行(从0开始)
        HSSFRow row = sheet.createRow(0);
        row.createCell(0).setCellValue("姓名");
        row.createCell(1).setCellValue("邮箱");
        row.createCell(2).setCellValue("年龄");
        //每个员工一行数据
        for (int i = 0; i < employees.size(); i++) {
            Employee employee = employees.get(i);
            row = sheet.createRow(i + 1);
            //创建单元格,写入内容
            row.createCell(0).setCellValue(employee.getName());
            row.createCell(1).setCellValue(employee.getEmail());
            row.createCell(2).setCellValue(employee.getAge());
            if (employee.getAge() != null) {
                row.createCell(2).setCellValue(employee.getAge());
            }
        }
        return wb;
    }

    @Override
    public void importXls(MultipartFile file) throws IOException {
        //把接收到的文件以excel的方式去读取并操作
        Workbook wb = new HSSFWorkbook(file.getInputStream());
        //读取第一页
        Sheet sheet = wb.getSheetAt(0);
        //获取最后一行的索引
        int lastRowNum = sheet.getLastRowNum();
        //从索引为1的行数开始读(忽略标题行)
        for (int i = 1; i <= lastRowNum; i++) {
            //获取行数据
            Row row = sheet.getRow(i);


            row.getCell(0).setCellType(CellType.STRING);
            String name = row.getCell(0).getStringCellValue();


            //判断如果用户名是空，就不再往下读
            if (!StringUtils.hasLength(name.trim())) {
                return;
            }
            Employee employee = new Employee();
            employee.setName(name);


            employee.setEmail(row.getCell(1).getStringCellValue());

            //方式一
            //获取文本格式的单元格内容
            // employee.setAge(Integer.valueOf(row.getCell(2).getStringCellValue()));


            //方式二
            //获取数值类型的单元格内容
            double value = row.getCell(2).getNumericCellValue();
            employee.setAge((int) value);
            //设置默认密码1
            employee.setPassword("1");
            //调用保存方法
            this.save(employee, null);
        }
    }

}